import { pageQuery, PageQueryResultPageItem } from '@/api/temu';
import { confirmMessage } from '@/lib/imperative';
import { concurrentLimit } from '@/lib/utils';
import {
  restoreKey,
  TemuAvailableSynchronizationTaskInfo,
} from '@/store/temuNotPersistAvaliableSynchronization';
import { toast } from 'sonner';
import { AvaliableSynchronizationTableDataItem } from './AvaliableSynchronization';
import { name } from '@/package.json';

export interface ResumeInfoData {
  currentTotal: number;
  tableData: AvaliableSynchronizationTableDataItem[];
}

type Props = {
  children?: React.ReactNode;
  className?: string;
  runBatchTask: (
    preprocessTableData: AvaliableSynchronizationTableDataItem[],
    isEnterQueue?: boolean,
  ) => Promise<void>;
  tableData: AvaliableSynchronizationTableDataItem[];
  currentTotal: number;
  resumeInfo: (resumeInfoData: ResumeInfoData) => void;
  container: string;
};

export default function AvaliableSynchronizationResume({
  children,
  className,
  runBatchTask,
  tableData,
  currentTotal,
  resumeInfo,
  container,
  ...props
}: Props) {
  useEffect(() => {
    const resumeTasks = JSON.parse(
      localStorage.getItem(restoreKey) || '[]',
    ) as TemuAvailableSynchronizationTaskInfo[];
    localStorage.setItem(restoreKey, '[]');
    // console.log(resumeTasks);
    async function resumeTask() {
      if (resumeTasks.length > 0) {
        const isResumeTask = await confirmMessage({
          title: '库存同步任务恢复',
          description: `检测到上次还有 ${resumeTasks.length} 个任务未完成，是否继续同步？`,
          confirmText: '继续同步',
          cancelText: '不同步',
          container: container,
        });
        if (isResumeTask) {
          // console.log(totalPageItems);
          await runBatchTask(resumeTasks);
          toast.success(`成功完成商品的库存同步任务`);
        }
      }
    }
    resumeTask();
  }, []);

  // 增加表格列表的恢复
  const localStorageKey = name + '-temu-avaliable-synchronization-table-data-task';
  useEffect(() => {
    function saveTableData(event: BeforeUnloadEvent) {
      // console.log(restQueue);
      try {
        localStorage.setItem(
          localStorageKey,
          JSON.stringify({
            currentTotal: currentTotal,
            tableData: tableData,
          }),
        );
      } catch (error) {
        console.log(error);
        toast.error(`localStorage 存储已经到达上限`);
      }
    }
    window.addEventListener('beforeunload', saveTableData);
    return () => {
      window.removeEventListener('beforeunload', saveTableData);
    };
  }, [currentTotal, tableData]);

  useEffect(() => {
    const resumeInfoData = JSON.parse(
      localStorage.getItem(localStorageKey) || '{}',
    ) as ResumeInfoData;
    localStorage.setItem(localStorageKey, '{}');
    if (resumeInfoData.currentTotal !== undefined) {
      console.log(resumeInfoData);
      resumeInfo(resumeInfoData);
    }
  }, []);

  return (
    <div className={className} {...props}>
      {/* AvaliableResume */}
    </div>
  );
}
